<?

namespace app\command;


use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Log;
use think\Db;
use app\common\model\TradeDetailsModel;

class Pledge extends Command
{
    protected function configure(){
        $this->setName('Pledge')->setDescription("Test auto exec");
    }

    protected function execute(Input $input, Output $output){
        while(true):
            //质押订单到时间计算
            Db::startTrans();
            try{
                $time=time();
                $list=db('users_pledge_orders')->where("end_time<=$time and status =1 ")->limit(5)->select();

                foreach($list as $val){
                    //给用户余额加钱
                    db('user_total')->where(['uid'=>$val['uid']])->setInc('balance',$val['total_award']);
                    db('user_total')->where(['uid'=>$val['uid']])->setInc('total_balance',$val['total_award']);

                    $userInfo=db('users')->where(['id'=>$val['uid']])->find();
                    $userTotal=db('user_total')->where(['uid'=>$val['uid']])->find();

                    //添加流水
                    $financial_data_p['uid'] 					= $val['uid'];
                    $financial_data_p['username'] 				= $userInfo['username'];
                    $financial_data_p['order_number'] 			= 'Z'.date('YmdHis').rand(0,9).rand(0,9).rand(0,9).rand(0,9);
                    $financial_data_p['trade_number'] 			= 'L'.trading_number();;
                    $financial_data_p['trade_type'] 			= 5;
                    $financial_data_p['trade_before_balance']	= $userTotal['balance'];
                    $financial_data_p['trade_amount'] 			= $val['total_award'];
                    $financial_data_p['account_balance'] 		= $userTotal['balance'] + $val['total_award'];
                    $financial_data_p['remarks'] 				= '碎片质押返利';
                    $financial_data_p['types'] 					= 1;
                    //p($financial_data_p);
                    $insert =  model('common/TradeDetails')->tradeDetails($financial_data_p);

                    db('users_pledge_orders')->where(['id'=>$val['id']])->update(['status'=>2]);

                    $output->writeln("pledge time out:".json_encode($val));

                }

                Db::commit();//事务提交
            } catch (\Exception $e) {
                error_log($e->getMessage());
                Db::rollback();
            }

            sleep(5);
            endwhile;
    }


}
